package com.haochang.chunkvod.model.order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.tools.thirdparty.network.http.httpenum.HttpMethodEnum;
import com.haochang.chunkvod.tools.thirdparty.network.http.httpenum.HttpRequestLoadingEnum;
import com.haochang.chunkvod.tools.thirdparty.network.http.request.HttpRequestBuilder;
import com.haochang.chunkvod.tools.thirdparty.network.http.request.HttpRequestTask;

import android.text.TextUtils;

/**
 * @author qintao
 *         created at 2016/6/25 15:12
 *         购物车请求数据处理
 */

public class ShopCartData
{

	private BaseActivity context;

	public ShopCartData(BaseActivity context)
	{
		this.context = context;
	}

	public interface IShopCartStatusListener
	{
		public void onRequestSuccess(List<GoodsInfo> list);
	}

	public interface IShopCartGoodsListener
	{
		public void onRequestSuccess(String message, String billId);

		public void onFail(int errno, String errMsg);
	}

	public interface IOrderGoodsChangeListener
	{
		public void onRequestSuccess();

		public void onFail(int errno, String errMsg);
	}

	/**
	 * 查询购物车相应商品的状态
	 *
	 * @param bill_id    账单id
	 * @param goods_ids  商品ids
	 * @param active_ids 活动ids
	 * @param listener   网络请求监听
	 */
	public void requestShopCartStatus(String bill_id, String goods_ids, String active_ids, final IShopCartStatusListener listener)
	{
		JSONArray goodArray = new JSONArray();
		if (!TextUtils.isEmpty(goods_ids))
		{
			String[] goodIds = goods_ids.split(",");
			for (int i = 0; i < goodIds.length; i++)
			{
				if (!TextUtils.isEmpty(goodIds[i]))
					goodArray.put(goodIds[i]);
			}
		}
		JSONArray activeArray = new JSONArray();
		if (!TextUtils.isEmpty(active_ids))
		{
			String[] activeIds = active_ids.split(",");
			for (int i = 0; i < activeIds.length; i++)
			{
				if (!TextUtils.isEmpty(activeIds[i]))
					activeArray.put(activeIds[i]);
			}
		}
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("goods_ids", goodArray.toString());
		if (!TextUtils.equals(bill_id, VodConstant.TAKEOUT_BILLID) && !TextUtils.isEmpty(bill_id))//外带不传active_ids,外带不传bill_id
		{
			map.put("active_ids", activeArray.toString());
			map.put("bill_id", bill_id);
		}
		HttpRequestTask httpRequestTask = new HttpRequestBuilder(context).interfaceName(ApiConfig.SHOPCARTSTATUS).param(map).httpMethodEnum(HttpMethodEnum.GET)
				.httpRequestLoadingEnum(HttpRequestLoadingEnum.HTTP_LOADING_DEFAULT).httpRequestSucessListener(new HttpRequestBuilder.IHttpRequestSucessListener()
				{

					@Override
					public void onResponseSucess(JSONObject jsonObject)
					{
						if (jsonObject != null)
						{
							List<GoodsInfo> list = parseGoodsStatusJson(jsonObject);
							if (listener != null)
							{
								listener.onRequestSuccess(list);
							}
						}
					}
				}).build();
		httpRequestTask.execute();
	}

	/**
	 * 提交商品订单
	 *
	 * @param bill_id       账单id
	 * @param goodArray     商品
	 * @param present_token 赠送审核人
	 * @param is_printed    是否列印 0：不列印；1：列印
	 * @param listener      网络请求监听
	 */
	public void requestShopCartGoods(JSONObject deskInfo, final String roomId, final String bill_id, String address, JSONArray goodArray, String present_token,
			int is_printed, final IShopCartGoodsListener listener)
	{
		if (null != goodArray)
		{
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("foods",
					TextUtils.equals(bill_id, VodConstant.TAKEOUT_BILLID) ? goodArray.toString().replace("food_id", "goods_id") : goodArray.toString());
			if (TextUtils.isEmpty(bill_id) && null != deskInfo)
				map.put("desk_info", deskInfo.toString());
			else if (TextUtils.equals(bill_id, VodConstant.TAKEOUT_BILLID) && !TextUtils.isEmpty(address))
			{//外带
				map.put("send_place", address);
			} else
			{
				map.put("bill_id", bill_id);
			}
			if (!TextUtils.isEmpty(present_token))
				map.put("present_token", present_token);
			map.put("is_printed", String.valueOf(is_printed));
			HttpRequestTask httpRequestTask = new HttpRequestBuilder(context)
					.interfaceName(TextUtils.equals(bill_id, VodConstant.TAKEOUT_BILLID) ? ApiConfig.TAKE_OUT_PLACE_AN_ORDER : ApiConfig.SUREGOODS).param(map)
					.httpMethodEnum(HttpMethodEnum.POST).httpRequestLoadingEnum(HttpRequestLoadingEnum.HTTP_LOADING_DEFAULT)
					.httpRequestSucessListener(new HttpRequestBuilder.IHttpRequestSucessListener()
					{

						@Override
						public void onResponseSucess(JSONObject jsonObject)
						{
							if (listener != null)
							{
								String message = "";
								String billId = "";
								if (jsonObject != null)
								{
									JSONArray jsonArray = jsonObject.optJSONArray("promotions");
									billId = jsonObject.optString("bill_id");
									if (!TextUtils.isEmpty(billId))
										EventProxy.notifyEvent(IEventConstant.EVENT_DESK_ID, billId, roomId);
									if (jsonArray != null && jsonArray.length() > 0)
									{
										for (int i = 0; i < jsonArray.length(); i++)
										{
											if (i == jsonArray.length() - 1)
												message += jsonArray.optString(i);
											else
												message += jsonArray.optString(i) + "、";
										}
									}
								}
								listener.onRequestSuccess(message, billId);
							}
						}
					}).httpRequestFailedListener(new HttpRequestBuilder.IHttpRequestFailedListener()
					{

						@Override
						public void onError(int errno, String errMsg)
						{
							if (listener != null)
								listener.onFail(errno, errMsg);
						}
					}).build();
			httpRequestTask.execute();
		}
	}

	/**
	 * 提交商品订单
	 *
	 * @param bill_retail_id // 被更换的套餐、包段中的单品id
	 * @param goodsInfo      更换的商品
	 * @param listener       网络请求监听
	 */
	public void requestChangeGoods(String bill_retail_id, GoodsInfo goodsInfo, final IOrderGoodsChangeListener listener)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("bill_retail_id", bill_retail_id);
		map.put("goods_id", goodsInfo.getGoodsId());
		map.put("quantity", String.valueOf(goodsInfo.getOrderNum()));
		JSONArray standard = null;
		try
		{
			String goodsStandard = goodsInfo.getStandard();
			standard = new JSONArray();
			if (!TextUtils.isEmpty(goodsStandard))
			{
				JSONArray array = new JSONArray(goodsStandard);
				if (array.length() > 0)
				{
					for (int i = 0; i < array.length(); i++)
					{
						JSONObject obj = array.optJSONObject(i);
						standard.put(obj.optString("name"));
					}
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		if (standard != null && standard.length() > 0)
			map.put("standards", standard.toString());
		HttpRequestTask httpRequestTask = new HttpRequestBuilder(context).interfaceName(ApiConfig.GOODS_SWAP).param(map).httpMethodEnum(HttpMethodEnum.POST)
				.httpRequestLoadingEnum(HttpRequestLoadingEnum.HTTP_LOADING_DEFAULT)
				.httpRequestSucessListener(new HttpRequestBuilder.IHttpRequestSucessListener()
				{

					@Override
					public void onResponseSucess(JSONObject jsonObject)
					{
						if (listener != null)
						{
							listener.onRequestSuccess();
						}
					}
				}).httpRequestFailedListener(new HttpRequestBuilder.IHttpRequestFailedListener()
				{

					@Override
					public void onError(int errno, String errMsg)
					{
						if (listener != null)
							listener.onFail(errno, errMsg);
					}
				}).build();
		httpRequestTask.execute();
	}

	private List<GoodsInfo> parseGoodsStatusJson(JSONObject jsonObject)
	{
		ArrayList<GoodsInfo> infoList = new ArrayList<GoodsInfo>();
		ArrayList<GoodsInfo> goodsList = new ArrayList<GoodsInfo>();
		ArrayList<GoodsInfo> activeList = new ArrayList<GoodsInfo>();
		JSONArray goodsArray = jsonObject.optJSONArray("goods");
		if (goodsArray != null && goodsArray.length() > 0)
		{
			for (int i = 0; i < goodsArray.length(); i++)
			{
				JSONObject jObject = goodsArray.optJSONObject(i);
				if (jObject == null)
					continue;
				GoodsInfo info = new GoodsInfo();
				info.setGoodsId(jObject.optString("goods_id"));
				info.setSurplus(jObject.optInt("rest_count"));
				info.setPrice(jObject.optInt("sale_price"));
				goodsList.add(info);
			}
		}

		JSONArray activeArray = jsonObject.optJSONArray("actives");
		if (activeArray != null && activeArray.length() > 0)
		{
			for (int i = 0; i < activeArray.length(); i++)
			{
				JSONObject jObject = activeArray.optJSONObject(i);
				if (jObject == null)
					continue;
				GoodsInfo info = new GoodsInfo();
				info.setGoodsId(jObject.optString("active_id"));
				info.setSurplus(jObject.optInt("rest_count"));
				info.setPrice(jObject.optInt("sale_price"));
				activeList.add(info);
			}
		}
		if (!CollectionUtils.isEmpty(goodsList))
			infoList.addAll(goodsList);
		if (!CollectionUtils.isEmpty(activeList))
			infoList.addAll(activeList);
		return infoList;
	}

}
